package com.mc.mcgoweb.utils.encrypt.rsaencrypt;


import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

/**
 * 非对称性加密
 * 请求数据解密
 */
@ControllerAdvice(basePackages = "com.mc.mcgoweb.com.mc.common.utils.encrypt.rsaencrypt")
public class RsaDecodeRequestBodyAdvice implements RequestBodyAdvice {
    /**
     *
     */
    private static final Logger logger = LoggerFactory.getLogger(RsaDecodeRequestBodyAdvice.class);

    private static final String PRIVATE_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANQW3xDKXiEeU44c" +
            "lGpfbYxq4MUrQ5fpRSeqp4R7dB12YZ+F0fENMUeBlz4uESqeufqVQkhaLwIQMnmK" +
            "vkexLb+mr7UDHn0ciMmUS1O35uO3pMJnM1xneEyzP961tImvJxAXveAs9bkf7Q76" +
            "lr57G97qfVtlV86WgYMfvdIVkEsDAgMBAAECgYArIOeFk5FmrLMTEA7CPtuZFVbV" +
            "4YFiT+ZnNZXRJAWtxBgAB4d0vFkMEHdABsAo6ZQqN9X9vpEWm1KYUrV1ALurgWc8" +
            "Zf3WNZ7YVHLRMuKhWwpljbhU0AJDJf+6Y5g9rVGJKpnrh/wbvZH9boXDEiOtBi7V" +
            "S1ddas0WPJ0c/kjEaQJBAPpvbDF9BY3jpJ9H1BmixJKpg2JFx5Eb7+fYugUT3i7x" +
            "PeCxx22TMzjY0pSZmIk2El6DIXdiS0HxCWQQ3DvprycCQQDYzVJXnB9+aY8BSRSq" +
            "48iEg16sc/o3cTh3DtnJkXN57L2GL+tM9ojd9btXdonafJF7P8EP9zotxX3yFp46" +
            "0K7FAkEAr7uoTEHSt/JZ/ntE1ohlMBVLYJZep/DWs/Zc8lsyufYG2blmm/mDJAzi" +
            "F+yAISiUU0XpIgETlj4xvMooANLGWQJBAKn+HFF7piodpLbSUbVJE8HrrAE2kvyD" +
            "901LRLNLLCtu2JBt5Gcda+X2NuX2mVLKl9v2+m+FX4XiM8XtvDXLyS0CQQDXp3bT" +
            "93+QAxiy891KSLY7U9NtfkweviFowRIMza8VZE5b4r8xvdSjAw60yLdaYH6rajOK" +
            "DcYDXYG+EE0cPn6h";

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        try {
            boolean encode = false;
            if (methodParameter.getMethod().isAnnotationPresent(RsaSecurityParameter.class)) {
                //获取注解配置的包含和去除字段
                RsaSecurityParameter serializedField = methodParameter.getMethodAnnotation(RsaSecurityParameter.class);
                //入参是否需要解密
                encode = serializedField.inDecode();
            }
            if (encode) {
                logger.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密");
                return new MyHttpInputMessage(inputMessage);
            } else {
                return inputMessage;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密出现异常：" + e.getMessage());
            return inputMessage;
        }
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }

    class MyHttpInputMessage implements HttpInputMessage {
        private HttpHeaders headers;

        private InputStream body;

        public MyHttpInputMessage(HttpInputMessage inputMessage) throws Exception {
            this.headers = inputMessage.getHeaders();
            String content = easpString(IOUtils.toString(inputMessage.getBody(), "utf-8"));
            this.body = IOUtils.toInputStream(RSAUtils.decryptDataOnJava(content, PRIVATE_KEY));
        }

        @Override
        public InputStream getBody() throws IOException {
            return body;
        }

        @Override
        public HttpHeaders getHeaders() {
            return headers;
        }

        /**
         * @param requestData
         * @return
         */
        public String easpString(String requestData) {
            if (requestData != null && !requestData.equals("")) {
                String s = "{\"requestData\":";
                if (!requestData.startsWith(s)) {
                    throw new RuntimeException("参数【requestData】缺失异常！");
                } else {
                    int closeLen = requestData.length() - 1;
                    int openLen = "{\"requestData\":".length();
                    String substring = StringUtils.substring(requestData, openLen, closeLen);
                    return substring;
                }
            }
            return "";
        }
    }
}
